#!/bin/bash

get_gpio()
{
    local NET_NAME=$1
    local RET_VAL

    mapfile -t -d " " GPIO_INFO < <(gpiofind "$NET_NAME")
    if [ "${#GPIO_INFO[@]}" -ne 2 ]; then
        echo "get_gpio: can not find gpio, $NET_NAME" >&2
        return 1
    fi
    for _ in {1..10}
    do
        if ! RET_VAL=$(gpioget "${GPIO_INFO[0]}" "${GPIO_INFO[1]%$'\n'}") ; then
            usleep 10000
            continue
        else
            echo "${RET_VAL}"
            return 0
        fi
    done

    echo "get_gpio: get ${NET_NAME} failed" >&2
    return 1
}

set_gpio()
{
    local NET_NAME=$1
    local OUT_VAL=$2
    mapfile -t -d " " GPIO_INFO < <(gpiofind "$NET_NAME")
    if [ "${#GPIO_INFO[@]}" -ne 2 ]; then
        echo "set_gpio: can not find gpio, $NET_NAME"
        return 1
    fi

    echo -n "set_gpio: set $NET_NAME = $OUT_VAL"
    if ! gpioset "${GPIO_INFO[0]}" "${GPIO_INFO[1]%$'\n'}"="$OUT_VAL"; then
        echo " failed"
        return 1
    fi

    echo " success"
    return 0
}

bind_i2c_device()
{
    local DRIVER_NAME="$1"
    local DEV_BUS_ADDR="$2"
    local DRIVER_DIR_PATH="/sys/bus/i2c/drivers/${DRIVER_NAME}"
    local DRIVER_BIND_PATH="${DRIVER_DIR_PATH}/bind"
    local MAX_RETRIES=1
    local RETRY=0

    if [ -n "$3" ]; then
        MAX_RETRIES="$3"
    fi

    if [ -L "${DRIVER_DIR_PATH}/${DEV_BUS_ADDR}" ]; then
        return 0
    fi

    while [ "$RETRY" -lt "$MAX_RETRIES" ]
    do
        if echo "${DEV_BUS_ADDR}" > "${DRIVER_BIND_PATH}"; then
            echo "bind_i2c_device: $DRIVER_NAME, $DEV_BUS_ADDR successful"
            return 0
        fi

        RETRY=$((RETRY + 1))
        echo "bind_i2c_device: $DRIVER_NAME, $DEV_BUS_ADDR failed"
        usleep 50000
    done

    return 1
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    CMD=$1
    shift
    case "$CMD" in
        get_gpio)
            get_gpio "$@"
            ;;
        set_gpio)
            set_gpio "$@"
            ;;
        bind_i2c_device)
            bind_i2c_device "$@"
            ;;
        *)
            echo "Usage: $0 {get_gpio|set_gpio|bind_i2c_device} args..."
            exit 1
            ;;
    esac
fi
